# -*- coding: utf-8 -*-
"""
# --------------------------------------------------------
# @Author : Pan
# @E-mail : 
# @Date   : 2025-10-29 13:59:45
# @Brief  :
# --------------------------------------------------------
"""
import numpy as np
import requests
import base64
import json
import PIL.Image as Image
from io import BytesIO
from pybaseutils import image_utils, file_utils

url = 'http://192.168.68.102:9999/api'
stream_url = url.replace('api', 'api/stream')

image_file = "../../data/image1.jpg"

# 读取图像并编码
image_base64 = image_utils.read_image_base64(image_file)

# 构建符合服务器要求的消息格式
def build_message(question_text, image_base64=None):
    """
    构建符合服务器要求的消息格式
    
    Args:
        question_text: 用户问题文本
        image_base64: 图像的base64编码（可选）
    
    Returns:
        str: JSON格式的消息字符串
    """
    message = {
        "role": "user",
        "content": [
            {
                "type": "text",
                "pairs": question_text
            }
        ]
    }
    
    # 如果有图像，添加到消息中
    # if image_base64 and len(image_base64) > 10:
    #     message["content"].insert(0, {
    #         "type": "image",
    #         "pairs": image_base64
    #     })

    return json.dumps([message])

# 构建请求数据
data = {
    "image": image_base64,  # 保持向后兼容
    "question": build_message("描述这张图片的内容", image_base64),
    "params": "{}"
}

print("发送的消息格式:")
# print(data["question"])

# 调用标准API
response = requests.post(url, json=data)
print("标准API响应:")
print(response.json())

# 调用流式API
print("\n流式API响应:")
response = requests.post(stream_url, json=data, stream=True)
for line in response.iter_lines():
    if line:
        decoded_line = line.decode()
        if decoded_line.startswith('data: '):
            try:
                data_content = json.loads(decoded_line[6:])  # 去掉 'data: ' 前缀
                if 'chunk' in data_content and data_content['chunk']:
                    print(data_content['chunk'], end='', flush=True)
                if data_content.get('finished', False):
                    print()  # 换行
                    break
            except json.JSONDecodeError:
                print(f"解析错误: {decoded_line}")